import subprocess
import execjs
import requests
import json
from Crypto.Cipher import AES
import os

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
    "referer": "https://www.luffycity.com",
    "origin": "https://www.luffycity.com"
}


def get_play_url(vid):
    url = f"https://api.luffycity.com/api/v1/play/{vid}/?play_id={vid}"
    headers["authorization"] = "Token 0215d18d825ef0b24096ec2bb034d5cf06c09916"
    resp = requests.get(url=url, headers=headers)
    resp_json = resp.json()
    code = resp_json['code']
    if code == 0:
        vid = resp_json['data']["auth_info"]["vid"]
        token = resp_json['data']["auth_info"]["token"]
        # print(vid)
        return (vid, get_play_json_decrypt(vid), token)
    else:
        print("服务器异常")


def get_play_json_decrypt(vid):
    if not vid:
        print("vid id empty")
        return None

    try:
        url = f"https://player.polyv.net/secure/{vid}.json"
        # print(url)
        resp = requests.get(url=url, headers=headers)
        # print(resp.text)
        return resp.json()
    except requests.exceptions.RequestException as e:
        print(f"Request failed:{e}")
        return None


def main():
    vid, data, token = get_play_url("82939")

    process = subprocess.Popen(["node", "js/encrypt.js", json.dumps(data), vid], stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE, text=True, encoding="utf-8")
    stdout, stderr = process.communicate()
    # print(stdout)
    hls = json.loads(stdout)["hls"][0]
    # print(hls)
    resp = requests.get(url=hls, headers=headers).json()
    d = json.dumps(resp)
    # print(d)

    with open("js/m3u8_decrypt.js", "r", encoding="utf-8") as f:
        js = f.read()

    exec = execjs.compile(js)

    result = exec.call("decrypt_key", d, 101.5)
    # print(result)
    key = result["key"]
    value = result["value"][2:]
    # print(value)
    url = key + "?token=" + token
    # print(url)
    result = requests.get(url=url, headers=headers)
    key = result.content
    # print(content)
    iv = bytes.fromhex(value)
    # print(iv)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    result = exec.call("decrypt_list", d, 101.5)
    # print(result)
    for (i, url) in enumerate(result):
        # print(url)
        encrypted_text = requests.get(url=url, headers=headers).content
        # 解密
        decrypted = cipher.decrypt(encrypted_text)
        with open("./video/" + str(i + 1) + ".ts", "wb") as f:
            f.write(decrypted)
        print(str(i + 1) + ".ts 下载完成")


if __name__ == '__main__':
    main()
